package com.situ.mall.web.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Feign配置类
 */
@Configuration
public class FeignConfig {

    /**
     * Feign请求拦截器 - 传递Session信息
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    
                    // 传递Session ID
                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String sessionId = session.getId();
                        
                        // 从原始请求中复制所有Cookie
                        String originalCookies = request.getHeader("Cookie");
                        if (originalCookies != null) {
                            template.header("Cookie", originalCookies);
                        } else {
                            // 如果没有原始Cookie，则手动构造
                            template.header("Cookie", "MALL_SESSION=" + sessionId + "; SESSION=" + sessionId);
                        }
                        
                        // 也通过X-Session-Id头传递（作为备用）
                        template.header("X-Session-Id", sessionId);
                        
                        System.out.println("Feign传递Session: " + sessionId + ", Cookie: " + 
                            (originalCookies != null ? originalCookies : "MALL_SESSION=" + sessionId));
                    } else {
                        System.out.println("Feign调用时无Session!");
                    }
                    
                    // 传递其他必要的头信息
                    String userAgent = request.getHeader("User-Agent");
                    if (userAgent != null) {
                        template.header("User-Agent", userAgent);
                    }
                    
                    String contentType = request.getHeader("Content-Type");
                    if (contentType != null) {
                        template.header("Content-Type", contentType);
                    }
                }
            }
        };
    }
} 